package blocking;

import com.sun.jmx.remote.internal.ArrayQueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 薛剑
 * @date 2020-11-23 15:11
 */

class MyBlockingShareDat {
    private volatile boolean flag = true;
    private AtomicInteger atomicInteger=new AtomicInteger();
    Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    BlockingQueue<String> blockingQueue = null;

    public MyBlockingShareDat(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.toString()+"当前赋值的名字是");
    }


    //入队生产
    public  void offerpop() throws InterruptedException {
        String data = "";
        boolean result;
        while (flag) {
           data= atomicInteger.incrementAndGet() + "";
            result=blockingQueue.offer(data, 1l, TimeUnit.SECONDS);
            if (result) {
                System.out.println(Thread.currentThread().getName()+"该队列，入队成功---》"+data);
            }
            TimeUnit.SECONDS.sleep(1l);
        }
        System.out.println(Thread.currentThread().getName()+"生产结束");
    }

    //出队消费

    public  void setoff() throws InterruptedException {

        String data = null;
        while (flag) {
            data=blockingQueue.poll(2l, TimeUnit.SECONDS);
            System.out.println("队列正在出栈消费----->"+data);
            if (data == null || data.equalsIgnoreCase("")) {
                System.out.println("超出了2秒没有找到生产者生产的数据我跳出来了");
                flag = false;

                System.out.println();
                System.out.println();
                return;
            }
        }


    }

    //全部停止

    public  void  teststop() throws InterruptedException {

        this.flag = false;
        TimeUnit.SECONDS.sleep(2);
        System.out.println("超级管理员关闭工厂");

    }




}

public class TestBlockingQueue {

    public static void main(String[] args) throws InterruptedException {

        MyBlockingShareDat shareDat = new MyBlockingShareDat(new ArrayBlockingQueue<>(10));
        new Thread(()->{
            try {
                shareDat.offerpop();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"生产者").start();




       new Thread(()->{

           try {
               shareDat.setoff();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }

       },"消费者").start();


       TimeUnit.SECONDS.sleep(2);
shareDat.teststop();
    }



}
